package com.pswv2.backstage.role.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pswv2.backstage.role.service.RoleService;
import com.pswv2.bub.bsc.dao.po.Permission;
import com.pswv2.bub.bsc.dao.po.Role;
import com.pswv2.bub.bsc.dao.po.RolePermission;
import com.pswv2.bub.bsc.dao.po.User;
import com.pswv2.util.BackendErrorCode;
import com.pswv2.util.CommonResp;
import com.pswv2.util.ExtraSpringHibernateTemplate;
import com.pswv2.util.Sessions;
import com.pswv2.util.Strings;

@Controller
@RequestMapping(value = "roleAction", produces = { "text/json;charset=UTF-8" })
public class RoleAction {
	
	private static Class<?> poc = Role.class;
	private static Class<?> pocU = User.class;
	private static Class<?> pocP = Permission.class;
	private static Class<?> pocRP = RolePermission.class;
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	@Autowired
	private RoleService roleService;
/**
 * 添加角色
 * @param name
 * @param session
 * @return
 */
	@ResponseBody
	@RequestMapping(value={"add"})
	public String addStation(String name){
		Role entity = new Role();
		entity.setName(name); 
		roleService.add(entity);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	
	/**
	 * 	删除角色
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"remove"})
	public String remove(@RequestParam(value = "name[]")String[] name,HttpSession session){
		
		Role entity = roleService.queryByName(Strings.trimAndNotNull(name[0]));
		if (entity == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		extraSpringHibernateTemplate.getHibernateTemplate().delete(entity);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	
	/**
	 * 给成员添加角色
	 */
	@ResponseBody
	@RequestMapping(value={"gotoAddMember"})
	public String gotoAddMember(@RequestParam(value = "userIds[]") int[] userIds,
			@RequestParam(value = "roleName[]") String[]  roleNames,HttpSession session){
		Role entity = roleService.queryByName(Strings.trimAndNotNull(roleNames[0]));
		Integer roleId = entity.getRoleId();
		for(int  id:userIds){
			User entityA = extraSpringHibernateTemplate.findFirstOneByPropEq(pocU, "userId", id);
				entityA.setRoleId(roleId);
				extraSpringHibernateTemplate.getHibernateTemplate().update(entityA);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	
	/**
	 * 初始化成员角色
	 */
	@ResponseBody
	@RequestMapping(value={"gotoRemoveMember"})
	public String updUserRole(@RequestParam(value = "members[]") Integer[] members){
		for(Integer id:members){
				User entity = extraSpringHibernateTemplate.findFirstOneByPropEq(pocU, "userId", id);
				if (entity == null) {
					return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
				}
				entity.setRoleId(-1);
				extraSpringHibernateTemplate.getHibernateTemplate().update(entity);
		}
		
		return CommonResp.buildSuccessResp().toJsonString();
	}
	
	/**
	 * 通过角色查询成员
	 */
	@ResponseBody
	@RequestMapping(value={"getMember"})
	public String getMember(@RequestParam(value = "name[]")String[] name ,HttpSession session){
		if(name!=null&&!"".equals(name[0])){
			List<Role> entitys=(List<Role>) extraSpringHibernateTemplate.getHibernateTemplate().find("From Role where name=?", name[0]);
			Role role = entitys.get(0);
			if(role == null){
				return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
			}
			Integer roleId = role.getRoleId();
			List<User> listEntity =(List<User>) extraSpringHibernateTemplate.getHibernateTemplate().find("From User where roleId=?", roleId);
			return CommonResp.buildSuccessResp(listEntity).toJsonString();
		}
		return CommonResp.buildSuccessResp().toJsonString();
	} 
	
	/**
	 * 查询无角色的用户
	 */
	@ResponseBody
	@RequestMapping(value={"initUserName"})
	public String initUserName(HttpSession session){
		List<User> listEntity = (List<User>) extraSpringHibernateTemplate.getHibernateTemplate().find("From User where  roleId=?",-1);
		return CommonResp.buildSuccessResp(listEntity).toJsonString();
	} 
	
	/**
	 * 	通过Id查询
	 */
	@ResponseBody
	@RequestMapping(value={"queryById"})
	public String queryById(int id){
		Role entity = roleService.queryById(id);
		if(entity == null){
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		return CommonResp.buildSuccessResp(entity).toJsonString();
	} 
	
	/**
	 * 	查询所有角色
	 */
	@ResponseBody
	@RequestMapping(value={"queryAll"})
	public String queryAll(){
		List<Role> rolelist=roleService.queryAll();
		return CommonResp.buildSuccessResp(rolelist).toJsonString();
	} 
	
	/**
	 * 通过角色查询权限
	 */
	@ResponseBody
	@RequestMapping(value={"getRoleProvince"})
	public String getRoleProvince(@RequestParam(value = "name[]")String[] name,HttpSession session){
		List<Permission> arrayList=new ArrayList<Permission>();
		Role entity = roleService.queryByName(Strings.trimAndNotNull(name[0]));
		if(entity == null){
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		Integer roleId = entity.getRoleId();
		List<RolePermission> listEntityRP = extraSpringHibernateTemplate.findAllByPropEq(pocRP, "roleId", roleId);
		for(RolePermission EntityRP:listEntityRP){
			Integer provinceId = EntityRP.getProvinceId();
			Permission EntityP = extraSpringHibernateTemplate.findFirstOneByPropEq(pocP, "provinceId", provinceId);
			arrayList.add(EntityP);
		}
		return CommonResp.buildSuccessResp(arrayList).toJsonString();
	} 
	
	/**
	 * 查询该角色没有的权限
	 */
	@ResponseBody
	@RequestMapping(value={"findInitProvince"})
	public String findInitProvince(@RequestParam(value = "name[]")String[] name,HttpSession session){
		Role entity = roleService.queryByName(Strings.trimAndNotNull(name[0]));
		if(entity == null){
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		Integer roleId = entity.getRoleId();
		//sql语句
		List<Permission> find = (List<Permission>) extraSpringHibernateTemplate.getHibernateTemplate().find("FROM Permission p WHERE p.provinceId NOT IN (select rp.provinceId FROM RolePermission rp WHERE rp.roleId=?)", roleId);
		return CommonResp.buildSuccessResp(find).toJsonString();
	} 
	
	/**
	 * 给角色添加权限
	 */
	@ResponseBody
	@RequestMapping(value={"addRoleProvince"})
	public String addRoleProvince(@RequestParam(value = "provinceIds[]") int[] provinceIds
			,@RequestParam(value = "roleName[]") String[]  roleNames,HttpSession session){
		Role entity = roleService.queryByName(Strings.trimAndNotNull(roleNames[0]));
		Integer roleId = entity.getRoleId();
		for(int id:provinceIds){
			RolePermission entityRP = new RolePermission();
			entityRP.setRoleId(roleId);
			entityRP.setProvinceId(id);
			extraSpringHibernateTemplate.getHibernateTemplate().save(entityRP);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	
	/**
	 * 	移除角色权限
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"removeRoleProvince"})
	public String removeRoleProvince(@RequestParam(value = "provinceIds[]")Integer[] provinceIds,@RequestParam(value = "roleName[]")String[] roleName){
		Role entityR = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "name", roleName[0]);
		Integer roleId = entityR.getRoleId();
		for(Integer id:provinceIds){
				List<Criterion> criterions = new ArrayList<>();
				criterions.add(Restrictions.eq("roleId",roleId));
				criterions.add(Restrictions.eq("provinceId",id));
				Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
				DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.build(pocRP, criterion);
				List<RolePermission> listEntity = extraSpringHibernateTemplate.findAllByCriteria(queryCountCriteria);
				if (listEntity.size()<=0) {
					return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
				}
				extraSpringHibernateTemplate.getHibernateTemplate().delete(listEntity.get(0));
		}
		
		return CommonResp.buildSuccessResp().toJsonString();
	}
}
